﻿// This source is subject to Microsoft Public License (Ms-PL).
// Please see http://taskcardcreator.codeplex.com for details.
// All other rights reserved.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using WorkItemReportInterface;

namespace TaskCardCreator
{
  /// <summary>
  /// Interaction logic for TaskCardDetailsPopup.xaml
  /// </summary>
  public partial class TaskCardDetailsPopup : Window
  {
    private List<IWorkItemReport> localReportList = new List<IWorkItemReport>();

    public IWorkItemReport SelectedReport;

    public ObservableCollection<WorkItem> WorkItems { get; set; }

    public WorkItemStore workItemStoreService;

    private BackgroundWorker worker;

    private string pendingRequest = string.Empty;

    public TaskCardDetailsPopup(IEnumerable<IWorkItemReport> reports)
    {
      WorkItems = new ObservableCollection<WorkItem>();

      InitializeComponent();

      listView.DataContext = this;

      foreach (var report in reports)
      {
        reportListBox.Items.Add(report.Description);
        localReportList.Add(report);
      }
      reportListBox.SelectedIndex = 0;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      var selectedItem = reportListBox.SelectedItem;

      SelectedReport = (from r in localReportList
                        where r.Description == selectedItem
                        select r).FirstOrDefault();

      DialogResult = true;
      Close();
    }

    private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
    {
      System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(e.Uri.AbsoluteUri));
      e.Handled = true;
    }

    void queries_SelectionChanged(string queryString)
    {
      Logger.Write("Entering queries_SelectionChanged method");

      progress.Visibility = Visibility.Visible;

      WorkItems.Clear();

      if (worker == null)
      {
        worker = new BackgroundWorker();
        worker.WorkerSupportsCancellation = false;
        worker.WorkerReportsProgress = false;

        worker.DoWork += bw_DoWork;
        worker.RunWorkerCompleted += bw_RunWorkerCompleted;
      }

      if (worker.IsBusy)
      {
        pendingRequest = queryString;
      }
      else
      {
        worker.RunWorkerAsync(queryString);
      }
    }

    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
      Logger.Write("Entering bw_DoWork method");

      var newWorkItems = new ObservableCollection<WorkItem>();

      var q = new Query(workItemStoreService, (string)e.Argument);
      if (q.IsLinkQuery)
      {
        var queryResults = q.RunLinkQuery();
        foreach (WorkItemLinkInfo i in queryResults)
        {
          var wi = workItemStoreService.GetWorkItem(i.TargetId);
          newWorkItems.Add(wi);
        }
      }
      else
      {
        var queryResults = q.RunQuery();
        foreach (WorkItem workitem in queryResults)
        {
          newWorkItems.Add(workitem);
        }
      }
      e.Result = newWorkItems;
    }

    private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      Logger.Write("Entering bw_RunWorkerCompleted method");

      if (e.Cancelled == true)
      {
      }
      else if (e.Error != null)
      {
        Logger.Write(string.Format("Exception: {0}", e.Error.Message));
        MessageBox.Show(string.Format("Error: {0}", e.Error.Message));
      }
      else
      {
        var newWorkItems = (ObservableCollection<WorkItem>)e.Result;
        Logger.Write(string.Format("Work items loaded: {0}", newWorkItems.Count));
        foreach (var item in newWorkItems)
        {
          WorkItems.Add(item);
        }

        listView.SelectAll();
      }
      progress.Visibility = Visibility.Collapsed;

      // Any pending requests?
      if (pendingRequest != string.Empty)
      {
        queries_SelectionChanged((string)pendingRequest.Clone());
        pendingRequest = string.Empty;
      }
    }

  }
}